package com.accompany.fragment.my;

import static android.content.Context.MODE_PRIVATE;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.accompany.R;
import com.accompany.api.bean.AountMoneyBean;
import com.accompany.api.bean.UserInforBean;
import com.accompany.api.category.UserInforMsgCategory;
import com.accompany.api.presenter.UserInforMsgPresenter;
import com.accompany.base.BaseFragment;
import com.accompany.dialog.LoginOutDialog;
import com.accompany.fragment.login.UserLoginActivity;
import com.accompany.fragment.my.activity.AuthenticationActivity;
import com.accompany.fragment.my.activity.BaozhenjingActivity;
import com.accompany.fragment.my.activity.ExtractMoneyActivity;
import com.accompany.fragment.my.activity.ExtractMoneyRecordActivity;
import com.accompany.fragment.my.activity.MyCardActivity;
import com.accompany.fragment.my.activity.RecruitAccompanyingMemberActivity;
import com.accompany.fragment.my.activity.ShouRuMingxiActivity;
import com.accompany.fragment.my.activity.TrainingCenterActivity;
import com.accompany.fragment.my.activity.TuijianPriendActivity;
import com.accompany.fragment.my.activity.UserPersonalActivity;
import com.accompany.fragment.my.activity.UserSettingActivity;
import com.accompany.fragment.order.activity.MineCommentsActivity;
import com.accompany.main.ConstantStaticUrl;
import com.accompany.main.MainActivity;
import com.accompany.utils.GlideCacheUtil;
import com.accompany.utils.HttpNetworkConnectUtils;
import com.accompany.utils.SPUtils;
import com.accompany.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 信息说明: 我的界面
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/3/14 15 ：40
 * 项目名称：yuanban
 */
public class MyFragment extends BaseFragment implements UserInforMsgCategory.View , OnRefreshListener {
    @BindView(R.id.account_money)
    TextView mAccountMoney;
    @BindView(R.id.user_mobile)
    TextView mUserMobile;
    @BindView(R.id.user_name)
    TextView mUserName;
    @BindView(R.id.icon_my)
    CircleImageView mIconImage;
    @BindView(R.id.no_login)
    TextView mNoLogin;
    @BindView(R.id.my_person)
    RelativeLayout mLinearPerson;
    @BindView(R.id.service)
    TextView service;
    @BindView(R.id.refresh_parent)
    SmartRefreshLayout refreshParent;
    private boolean isOnClick = false;
    private UserInforMsgPresenter mPesenter;
    private String mToken;
    private long mUserId;
    private double mPrice = 0.0;
    private String mIconAvatar;
    private String mSfzCardId;
    private String mUserNickName;
    private String mUserPhone;
    private LoginOutDialog dialog;
    private boolean isLogin;
    @Override
    public int getLayoutResource() {
        return R.layout.fragment_my_view;
    }

    @Override
    public void onResume() {
        super.onResume();
        //判断是不是登录状态
        checkIsLogin();
    }

    @Override
    public void initLayoutView() {
        mPesenter = new UserInforMsgPresenter(this);
        SetPersenter(mPesenter);
        mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        refreshParent.setPrimaryColors(0xffff512f, 0xffffffff);
        refreshParent.setEnableLoadMore(false);
        refreshParent.setOnRefreshListener(this);
        if (!HttpNetworkConnectUtils.isNetworkConnected(getActivity())) {
            ToastUtil.showToastERROR(getActivity(), "网络不给力,请稍后重试");
        } else {
            mPesenter.getMoneyPrice(mToken, mUserId);
            mPesenter.UserInforMsg(mToken, String.valueOf(mUserId));
        }
    }

    @OnClick({R.id.pxzx_my, R.id.tjhy_my, R.id.my_person, R.id.no_login, R.id.mingxi, R.id.liji_tixian, R.id.baozhengjin, R.id.my_setting, R.id.my_jiuzhen, R.id.relat_yue, R.id.tixian, R.id.my_kabao, R.id.service,R.id.my_dianping,R.id.my_zhaomu})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.pxzx_my:
                openActivityWitchAnimation(TrainingCenterActivity.class);
                break;
            case R.id.my_person:
                Intent intent = new Intent(getActivity(), UserPersonalActivity.class);
                intent.putExtra("mobile", mUserPhone);
                intent.putExtra("nickName", mUserNickName);
                intent.putExtra("iconImage", mIconAvatar);
                intent.putExtra("mSfzCardId", mSfzCardId);
                intent.putExtra("stateType", "0");
                startActivityForResult(intent, 100);
                break;
            case R.id.no_login:
                openActivityWitchAnimation(UserLoginActivity.class);
                SPUtils.clear(getActivity());
                getActivity().finish();
                break;
            case R.id.mingxi:
                Bundle bundle = new Bundle();
                bundle.putDouble("amount",mPrice);
                openActivityWitchAnimation(ShouRuMingxiActivity.class,bundle);
                break;
            case R.id.baozhengjin:
                openActivityWitchAnimation(BaozhenjingActivity.class);
                break;
            case R.id.tjhy_my:
                openActivityWitchAnimation(TuijianPriendActivity.class);
                break;
            case R.id.my_jiuzhen:
                openActivityWitchAnimation(AuthenticationActivity.class);
                break;
            case R.id.relat_yue:
                if (isOnClick == true) {
                    mAccountMoney.setText("******");
                } else {
                    mAccountMoney.setText("￥" + mPrice);
                }
                isOnClick = !isOnClick;
                break;
            case R.id.tixian:
                openActivityWitchAnimation(ExtractMoneyRecordActivity.class);
                break;
            case R.id.my_setting:
                openActivityWitchAnimation(UserSettingActivity.class);
                break;
            case R.id.my_kabao:
                openActivityWitchAnimation(MyCardActivity.class);
                break;
            case R.id.liji_tixian:
                openActivityWitchAnimation(ExtractMoneyActivity.class);
                break;
            case R.id.service:
                customerService();
                break;
            case R.id.my_zhaomu:
                openActivityWitchAnimation(RecruitAccompanyingMemberActivity.class);
                break;
            case  R.id.my_dianping:
                SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
                mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
                Bundle bun = new Bundle();
                bun.putString("orderId",null);
                bun.putLong("acdId",mUserId);
                openActivityWitchAnimation(MineCommentsActivity.class,bun);
                break;
        }
    }

    //客服中心打电话
    private void customerService() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 若没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.CALL_PHONE)) {
                // 如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                //  如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                // 如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                // 弹窗需要解释为何需要该权限，再次请求授权
                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent call = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                call.setData(uri);
                startActivity(call);
            } else {
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.CALL_PHONE},
                        0);
            }
        } else {
            // 已经获得授权，可以打电话
            // 通过intent跳转到拨打电话的界面
            Intent intent1 = new Intent();
            intent1.setAction(Intent.ACTION_CALL);
            Uri phoneNum = Uri.parse("tel:" + "0931-8797777");
            intent1.setData(phoneNum);
            startActivity(intent1);
        }
    }

    @Override
    public void UserInforMsg(UserInforBean userinfor) {
        if (userinfor.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            mNoLogin.setVisibility(View.GONE);
            mLinearPerson.setVisibility(View.VISIBLE);
            if (userinfor.getData() != null) {
                mIconAvatar = userinfor.getData().getAcdImg();
                RequestOptions requestOptions = new RequestOptions();
                requestOptions.error(R.drawable.head_icon)
                        .circleCrop()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE);
                Glide.with(getActivity())
                        .load(userinfor.getData().getAcdImg())
                        .apply(requestOptions)
                        .into(mIconImage);
                if (userinfor.getData().getAcdName() != null || userinfor.getData().getAcdPhone() != null) {
                    mUserPhone = userinfor.getData().getAcdPhone();
                    mUserNickName = userinfor.getData().getAcdName();
                    mSfzCardId = userinfor.getData().getCertificateType();
                    SPUtils.put(getActivity(), "account", userinfor.getData().getAccount());
                    SPUtils.put(getActivity(), "nickname", userinfor.getData().getAcdName());
                    SPUtils.put(getActivity(), "mUserPhone", userinfor.getData().getAcdPhone());
                    String mMobile = (String) SPUtils.get(getActivity(), "mUserPhone", "");
                    String name = (String) SPUtils.get(getActivity(), "nickname", "");
                    mUserMobile.setText("手机号码 : " + mMobile);
                    mUserName.setText(name);
                } else {
                    mUserMobile.setText("");
                    mUserName.setText("");
                }
            }
        } else if (userinfor.getCode() == 401) { //未授权  没有登录
            mNoLogin.setVisibility(View.VISIBLE);
            mLinearPerson.setVisibility(View.GONE);
            dialog = LoginOutDialog.getLoginOutDialog(getActivity() );
            dialog.show();
            dialog.findViewById(R.id.circler_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    dialog = null;
                }
            });
            dialog.findViewById(R.id.to_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivityWitchAnimation(UserLoginActivity.class);
                    SPUtils.clear(getActivity());
                    getActivity().finish();
                    dialog.dismiss();
                    dialog = null;
                }
            });

        } else {
            ToastUtil.showToastINFO(getActivity(), userinfor.getMsg());
        }
    }

    @Override
    public void getMoneyPrice(AountMoneyBean bean) {
        if (bean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (bean.getData() != null) {
                mPrice = bean.getData().getAccount();
                SPUtils.put(getActivity(),"account",mPrice);
                mAccountMoney.setText("￥" + bean.getData().getAccount());
            } else {
                ToastUtil.showToastINFO(getActivity(), bean.getMsg());
            }
        }
    }

    /**
     * 判断是不是登录状态
     */
    private void checkIsLogin() {
        //从其他页面进入登录页面  需要返回
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        isLogin = sharedPreferences.getBoolean("isLogin",false);
        if (isLogin){//已经登录
            mPesenter.getMoneyPrice(mToken, mUserId);
            mNoLogin.setVisibility(View.GONE);
            mLinearPerson.setVisibility(View.VISIBLE);
        }else {//所有的信息为空
            mAccountMoney.setText("");
            mNoLogin.setVisibility(View.VISIBLE);
            mLinearPerson.setVisibility(View.GONE);
        }
    }

    @Override
    public void SetPersenter(Object persenter) {

    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 100 && resultCode == 200) {
            String nickName = data.getStringExtra("nickName");
            String iconImage = data.getStringExtra("iconImage");
            mUserName.setText(nickName);
            GlideCacheUtil.getInstance().clearImageAllCache(getActivity());
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.error(R.drawable.head_icon)
                    .circleCrop()
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE);
            Glide.with(getActivity())
                    .load(iconImage)
                    .apply(requestOptions)
                    .into(mIconImage);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPesenter.getMoneyPrice(mToken, mUserId);
        mPesenter.UserInforMsg(mToken, String.valueOf(mUserId));
        refreshParent.finishRefresh(300);
    }
}
